import { createRouter, createWebHistory } from 'vue-router'

import index from './components/index.vue'
import goods from "./components/goods.vue"
import user1 from './components/user1.vue'
import user2 from './components/user2.vue'
import goods1 from './components/goods1.vue'
import settings from './components/settings.vue'
import home from './home/index.vue'

// 创建路由实例对象
const router = createRouter({
    history: createWebHistory(),
    routes: [
        { path: '/', name:'index',component:index },
        { path: '/goods', name:'goods',component:goods },

        { path: '/rest/user1/:id', name:'user1',component:user1 },
        { path: '/rest/user2/:id/:username/:password', name:'user2',component:user2,props:true },
        { path: '/query/goods1', name:'goods1',component:goods1,props: route => ({ id: route.query.id,userName:route.query.userName,password:route.query.password }) },
        { path: '/home',  name:'home',component:home,
            children:[
                {
                    path: 'user/list',component:() => import('@/home/userList.vue'),
                },
                {
                    path: 'goods/list',component:() => import('@/home/goodsList.vue'),
                },
            ]
        },


        { path: '/404', name: 'PageNotExist',component: () => import('@/components/PageNotExist.vue')},
        {
            path: "/:catchAll(.*)", // 不识别的path自动匹配404
            redirect: '/404',
        },
        { path: '/login', name:'login',component: () => import('@/login/login.vue') },


    ],
})


// 全局路由导航守卫
router.beforeEach((to, from, next) => {

    // 判断用户访问的是否为登录页
    if (to.path === '/login' || to.path==='/register' || to.path==='/404') return next()
    // 获取 token 值
    const loginToken = localStorage.getItem('loginToken')

    if (!loginToken) {
        next('/login')
    } else {
        next()
    }
})


router.addRoute({ path: '/settings', component: settings })

export default router
